const { post } = require('../../utils/request.js')
const themeManager = require('../../utils/theme.js')

Page(themeManager.enhancePage({
  data: {
    isLoading: false,
    currentTheme: 'dark'
  },

  onLoad() {
    const token = wx.getStorageSync('token');
    if (token) {
      wx.reLaunch({ url: '/pages/index/index' });
    }
  },

  onLoginTap() {
    if (this.data.isLoading) return;

    this.setData({ isLoading: true });
    
    wx.login({
      success: (res) => {
        if (res.code) {
          post('/auth/wechat_login', { code: res.code })
            .then(resp => {
              if (resp && resp.status === 0 && resp.data && resp.data.token) {
                wx.setStorageSync('token', resp.data.token);
                console.log('登录成功，token:', resp.data.token);
                wx.reLaunch({ url: '/pages/index/index' });
              } else {
                wx.showToast({ 
                  title: resp.message || '登录失败', 
                  icon: 'none' 
                });
              }
            })
            .catch(err => {
              wx.showToast({ 
                title: err.message || '网络错误', 
                icon: 'none' 
              });
            })
            .finally(() => {
              this.setData({ isLoading: false });
            });
        } else {
          this.setData({ isLoading: false });
          wx.showToast({ 
            title: '获取登录凭证失败', 
            icon: 'none' 
          });
        }
      },
      fail: () => {
        this.setData({ isLoading: false });
        wx.showToast({ 
          title: '微信登录失败', 
          icon: 'none' 
        });
      }
    });
  }
}));